package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import android.widget.ProgressBar
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.ui.setInvisible

/**
 * 调节声音和亮度的提示进度条
 */
open class ExoPlayerCenterHintProgressBar : ProgressBar, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        config.currentVolume.observeForever(::onVolumeChange)
        config.screenBrightness.observeForever(::onScreenBrightnessChange)
        config.seekBarProgress.observeForever(::onSeekBarProgress)
    }

    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        config.currentVolume.removeObserver(::onVolumeChange)
        config.screenBrightness.removeObserver(::onScreenBrightnessChange)
        config.seekBarProgress.removeObserver(::onSeekBarProgress)
    }


    open fun onVolumeChange(fl: Float?) {
        setInvisible(fl != null)
        if (fl != null) {
            progress = (fl * max).toInt()
        }
    }

    open fun onScreenBrightnessChange(fl: Float?) {
        setInvisible(fl != null)
        if (fl != null) {
            progress = (fl * max).toInt()
        }
    }

    open fun onSeekBarProgress(pair: Pair<Boolean, Float>?) {
        setInvisible(pair?.first == false)
        pair?.second?.let {
            progress = (it * max).toInt()
        }
    }
}